package com.lagou.rpc.server;

import com.lagou.rpc.config.ZkConfig;
import com.lagou.rpc.entity.RpcRequest;
import com.lagou.rpc.protocol.JSONSerializer;
import com.lagou.rpc.protocol.RpcDecoder;
import com.lagou.rpc.protocol.RpcEncoder;
import com.lagou.rpc.service.impl.UserServiceImpl;
import com.lagou.rpc.zk.ZkClient;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class NettyServer implements CommandLineRunner {

    @Value("${server.port}")
    private int port;

    @Autowired
    private ZkClient zkClient;

    @Autowired
    private UserServiceImpl userService;
    /**
     * 启动netty server
     * 会向zookeeper写入临时节点。
     * @throws Exception
     */
    public void start() throws Exception {
        String host = "127.0.0.1";
        String url = host + ":" + port;
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(nioEventLoopGroup).channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(
                new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LengthFieldBasedFrameDecoder(
        65536, 0, 4, 0, 0));
                        p.addLast(new RpcDecoder(new JSONSerializer(), RpcRequest.class));
                        p.addLast(new RpcEncoder(new JSONSerializer()));
                        p.addLast(new RpcNettyHandler(zkClient, url));

                    }
                });
        bootstrap.bind(host, port).sync();
        userService.setPort(port);

        ZkConfig.serviceList().forEach(item -> {
            String path = "/rpc/" + item;
            if (!zkClient.exists(path)) {
                zkClient.create(path, false);
            }
            if(zkClient.exists(path + "/" + url)) {
                zkClient.delete(path + "/" + url);
            }
            zkClient.create(path + "/" + url, true);
        });
    }

    @Override
    public void run(String... args) throws Exception {
        start();
    }
}
